/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "hhdBulletPhysicsManager.h"
#include "hhdRigidBody.h"
#include "hhdBulletPhysicsDirector.h"
#include "hhdPhysicsEnums.h"
#include "btBulletCollisionCommon.h"
#include "btBulletDynamicsCommon.h"
#include "hhdMath.h"
#include "hhdFloat.h"

namespace hhd
{
    namespace BulletPhysics
    {
        HashTable<void*, BulletPhysicsDirector*>* BulletPhysicsManager::_dynamics_world_to_director_index = NULL;

        void BulletPhysicsManager::initialize()
        {
            _dynamics_world_to_director_index = new HashTable<void*, BulletPhysicsDirector*>(2);
        }

        void BulletPhysicsManager::finalize()
        {
            delete _dynamics_world_to_director_index;
        }

        void BulletPhysicsManager::preTickCallback(btDynamicsWorld* world, float timestep)
        {
            BulletPhysicsDirector* director = NULL;
            if(_dynamics_world_to_director_index->tryGetValue((void*)world, director))
            {
                // iterate over all ICollisionObjects* to cap velocity and apply forces
                IEnumerator<Pair<void*, ICollisionObject*> >* en = director->_index_enumerator;
                en->reset();
                while(en->moveNext())
                {
                    Pair<void*, ICollisionObject*>& p = en->current();
                    RigidBody* hh_rigid_body = p.second->as<RigidBody>();

                    // only dynamic objects have this sort of information
                    if(hh_rigid_body && hh_rigid_body->_type == Dynamic)
                    {
                        // get the bullet rigidbody
                        btRigidBody* bt_rigid_body = (btRigidBody*)p.first;


                        /** Apply Forces **/

                        bt_rigid_body->clearForces();
                        if(hh_rigid_body->_gravity_enabled)
                        {
                            bt_rigid_body->applyGravity();
                        }

                        // calculate local force in global space
                        btVector3 local_force = hh_rigid_body->_local_force;
                        if(local_force.isZero() == false)
                        {
                            local_force = bt_rigid_body->getWorldTransform().getBasis() * local_force;
                        }
                        // calculate global force
                        btVector3 global_force(hh_rigid_body->_global_force);
                        // total force
                        btVector3 total_force = global_force + local_force;

                        // apply total force
                        bt_rigid_body->applyCentralForce(total_force);

                        /** Appy Torques **/

                        // calculat local torque in global space
                        btVector3 local_torque = hh_rigid_body->_local_torque;
                        if(local_torque.isZero() == false)
                        {
                            local_torque = bt_rigid_body->getWorldTransform().getBasis() * local_torque;
                        }
                        // global torque
                        btVector3 global_torque(hh_rigid_body->_global_torque);
                        // total torque
                        btVector3 total_torque = global_torque + local_torque;
                        // apply torque
                        bt_rigid_body->applyTorque(total_torque);

                    }
                }
            }
        }

        void BulletPhysicsManager::postTickCallback(btDynamicsWorld* world, float timestep)
        {
            BulletPhysicsDirector* director = NULL;
            if(_dynamics_world_to_director_index->tryGetValue((void*)world, director))
            {
                // iterate over all ICollisionObjects* to cap velocity and apply forces
                IEnumerator<Pair<void*, ICollisionObject*> >* en = director->_index_enumerator;
                en->reset();
                while(en->moveNext())
                {
                    Pair<void*, ICollisionObject*>& p = en->current();
                    RigidBody* hh_rigid_body = p.second->as<RigidBody>();

                    // only dynamic objects have this sort of information
                    if(hh_rigid_body && hh_rigid_body->_type == Dynamic)
                    {
                        // get the bullet rigidbody
                        btRigidBody* bt_rigid_body = (btRigidBody*)p.first;

                        // cap speed using terminal velocity
                        if(hh_rigid_body->_max_speed != Float::Infinity)
                        {
                            float& max_speed = hh_rigid_body->_max_speed;

                            btVector3 velocity = bt_rigid_body->getLinearVelocity();
                            float speed = velocity.length();
                            if(speed > max_speed)
                            {
                                bt_rigid_body->setLinearVelocity(velocity * (max_speed / speed));
                            }
                        }
                        else if(hh_rigid_body->_max_piecewise_speed != Vector3::infinity)
                        {
                            Vector3& max_piecewise = hh_rigid_body->_max_piecewise_speed;
                            btVector3 velocity = bt_rigid_body->getLinearVelocity();
                            if(Math::abs(velocity.x()) > Math::abs(max_piecewise.x))
                            {
                                velocity.setX(Math::sign(velocity.x()) * Math::abs(max_piecewise.x));
                            }
                            if(Math::abs(velocity.y()) > Math::abs(max_piecewise.y))
                            {
                                velocity.setY(Math::sign(velocity.y()) * Math::abs(max_piecewise.y));
                            }
                            if(Math::abs(velocity.z()) > Math::abs(max_piecewise.z))
                            {
                                velocity.setZ(Math::sign(velocity.z()) * Math::abs(max_piecewise.z));
                            }
                            bt_rigid_body->setLinearVelocity(velocity);
                        }
                    }
                }
            }
        }
    }
}
